package com.dinadi.yidi.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dinadi.yidi.R;
import com.dinadi.yidi.adapter.MyShoppingCartsAdapter;
import com.dinadi.yidi.base.BaseActivity;
import com.dinadi.yidi.bean.CartItemListBean;
import com.dinadi.yidi.bean.MessageBean;
import com.dinadi.yidi.http.HttpListener;
import com.dinadi.yidi.http.UpdateView;
import com.dinadi.yidi.http.interfaces.CommonInterface;
import com.dinadi.yidi.ui.view.SmoothCheckBox;
import com.dinadi.yidi.utils.JsonUtil;
import com.dinadi.yidi.utils.SharePreferencesHelper;
import com.dinadi.yidi.utils.ToastUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * author: JiaYu.He
 * Date: 2017/11/2   我的购物车
 * Time: 16:21
 */
public class MyShoppingCartsActivity extends BaseActivity implements UpdateView, View.OnClickListener {
    private View view;
    private TextView tvTitle, tvRight, text_msg;
    private TextView mTvAllMoney, select_num;
    private ImageView img_no_comment;
    private SmoothCheckBox mCbSelectAll;
    private ExpandableListView mExpandableListView;
    private Button mBtnBuy;
    private RelativeLayout shopping_cart_message, layout_no_comment;
    private MyShoppingCartsAdapter mRefreshAdapter;
    private List<CartItemListBean.ContentBean> dataBean = new ArrayList<>();
    private String userId, token;
    /*是否显示没有的图片*/
    private boolean isShow = true;
    private CartItemListBean cartItemListBean;
    private String cartItemIds = "";
    /*0,结算 1，删除*/
    private String type = "0";

    @Override
    protected View getLayout() {
        view = LayoutInflater.from(MyShoppingCartsActivity.this).inflate(R.layout.activity_my_shopping_cart, null);
        return view;
    }

    @Override
    protected void noWifiRefresh() {

    }

    @Override
    protected void initView() {

        changePager(2);
        tvTitle = (TextView) view.findViewById(R.id.text_title);
        tvTitle.setText(getResources().getString(R.string.text_my_shopping_cart));
        tvRight = (TextView) view.findViewById(R.id.text_title_right);
        tvRight.setText(getResources().getString(R.string.text_edit));
        mExpandableListView = (ExpandableListView) findViewById(R.id.expandableListView);
        mCbSelectAll = (SmoothCheckBox) findViewById(R.id.cb_select_all);
        mTvAllMoney = (TextView) findViewById(R.id.tv_all_money);
        mBtnBuy = (Button) findViewById(R.id.btn_settlement);
        layout_no_comment = (RelativeLayout) view.findViewById(R.id.layout_no_comment);
        img_no_comment = (ImageView) view.findViewById(R.id.img_no_comment);
        select_num = (TextView) view.findViewById(R.id.select_num);
        text_msg = (TextView) view.findViewById(R.id.text_msg);
        shopping_cart_message = (RelativeLayout) view.findViewById(R.id.shopping_cart_message);

        //去掉ExpandableListView 默认的箭头
        mExpandableListView.setGroupIndicator(null);

        //用于列表滑动时，EditText清除焦点，收起软键盘
        mExpandableListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                if (SCROLL_STATE_TOUCH_SCROLL == scrollState) {
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity
                            .INPUT_METHOD_SERVICE);
                    View focusView = getCurrentFocus();
                    if (focusView != null) {
                        inputMethodManager.hideSoftInputFromWindow(focusView.getWindowToken(), InputMethodManager
                                .HIDE_NOT_ALWAYS);
                        focusView.clearFocus();
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });
        mExpandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                /*禁止group点击  */
                return true;
            }
        });


    }

    @Override
    protected void initListener() {
        mCbSelectAll.setOnClickListener(this);
        registerClickListener(mBtnBuy, tvRight);
        mRefreshAdapter.setOnClickListenerCallBack(new MyShoppingCartsAdapter.OnClickListenerCallBack() {
                                                       @Override
                                                       public void onClickClear(int position) {

                                                           for (int n = 0; n < cartItemListBean.getCartItemList().get(position).getCartItemList().size(); n++) {

                                                               cartItemIds += cartItemListBean.getCartItemList().get(position).getCartItemList().get(n).getId() + ",";

                                                           }
                                                           CartItemListBean bean = new CartItemListBean();
                                                           bean.setCartItemIds(cartItemIds);
                                                           bean.setToken(token);
                                                           CommonInterface commonInterface = new CommonInterface(MyShoppingCartsActivity.this, deleteHttpListener);
                                                           commonInterface.getInterface("16037", JSON.toJSONString(bean));

                                                       }
                                                   }

        );
    }

    @Override
    protected void initData() {
        userId = SharePreferencesHelper.getInstance(MyShoppingCartsActivity.this).getString("userId");
        token = SharePreferencesHelper.getInstance(MyShoppingCartsActivity.this).getString("token");
        showLoadingDialog(getResources().getString(R.string.dialog_text));
        initPullrefresh();
        mRefreshAdapter = new MyShoppingCartsAdapter(MyShoppingCartsActivity.this);
        mRefreshAdapter.setChangedListener(MyShoppingCartsActivity.this);


    }

    @Override
    public void onResume() {
        super.onResume();
        String isRefresh = SharePreferencesHelper.getInstance(MyShoppingCartsActivity.this).getString("isRefresh");
        String isShoppingRefresh = SharePreferencesHelper.getInstance(MyShoppingCartsActivity.this).getString("isShoppingRefresh");
        if ("yes".equals(isRefresh) || "yes".equals(isShoppingRefresh)) {
            userId = SharePreferencesHelper.getInstance(MyShoppingCartsActivity.this).getString("userId");
            token = SharePreferencesHelper.getInstance(MyShoppingCartsActivity.this).getString("token");
            showLoadingDialog(getResources().getString(R.string.dialog_text));
            initPullrefresh();
            SharePreferencesHelper.getInstance(this).putString("isRefresh", "no");
            select_num.setText("全选(0)");
        }
        mCbSelectAll.setChecked(false);

    }

    @Override
    protected void clickEvent(View v) {

        switch (v.getId()) {
            case R.id.cb_select_all:
                selectAll();
                break;
            case R.id.btn_settlement:
                if (cartItemListBean.getCartItemIds() != null && cartItemListBean.getCartItemIds().length() != 0) {

                    if (type.equals("1")) {
                        /*去删除*/
                        CartItemListBean bean = new CartItemListBean();
                        bean.setCartItemIds(cartItemListBean.getCartItemIds());
                        bean.setToken(token);
                        CommonInterface commonInterface = new CommonInterface(MyShoppingCartsActivity.this, deleteHttpListener);
                        commonInterface.getInterface("16037", JSON.toJSONString(bean));
                    } else {
                        /*去结算*/
                        Intent intent = new Intent(MyShoppingCartsActivity.this, OrderDetailsActivity.class);
                        intent.putExtra("isShoppingCart", "yes");
                        intent.putExtra("cartItemIds", cartItemListBean.getCartItemIds());
                        startActivity(intent);
                    }
                } else {
                    ToastUtil.showToast("您还没有选择宝贝哦~");
                }
//                if (cartItemListBean.getCartItemIds() != null & !"".equals(cartItemListBean.getCartItemIds())) {
//
//                }


                break;
            case R.id.text_title_right:
                /*编辑*/
                if (tvRight.getText().equals("编辑")) {
                    tvRight.setText("完成");
                    type = "1";
                    mBtnBuy.setBackground(getResources().getDrawable(R.drawable.img_delete));
                } else {
                    tvRight.setText("编辑");
                    type = "0";
                    mBtnBuy.setBackground(getResources().getDrawable(R.drawable.img_settlement));

                }
                break;
            default:
                break;

        }
    }

    /*全选*/
    private void selectAll() {
        int allCount = cartItemListBean.getAllCount();
        BigDecimal allMoney = cartItemListBean.getAllMoney();
        if (allMoney == null) {
            allMoney = new BigDecimal(0);
        }
        if (!mCbSelectAll.isChecked()) {
            /*全选*/
            cartItemListBean.setAllSelect(true);
            for (int i = 0; i < cartItemListBean.getCartItemList().size(); i++) {
                if (!cartItemListBean.getCartItemList().get(i).getUserName().equals("失效商品")) {
                    cartItemListBean.getCartItemList().get(i).setSelected(true);
                }
                for (int n = 0; n < cartItemListBean.getCartItemList().get(i).getCartItemList().size(); n++) {
                    if (!cartItemListBean.getCartItemList().get(i).getCartItemList().get(n).isSelected()) {
                        if (!cartItemListBean.getCartItemList().get(i).getUserName().equals("失效商品")) {
                            allCount++;
//                        allMoney += Integer.valueOf(cartItemListBean.getCartItemList().get(i).getCartItemList().get(n).getQuantity())
//                                * Double.parseDouble(cartItemListBean.getCartItemList().get(i).getCartItemList().get(n).getUnitPrice());
                            allMoney = allMoney.add(new BigDecimal(cartItemListBean.getCartItemList().get(i).getCartItemList().get(n).getQuantity()).multiply(new BigDecimal(cartItemListBean.getCartItemList().get(i).getCartItemList().get(n).getUnitPrice())));

                            cartItemListBean.getCartItemList().get(i).getCartItemList().get(n).setSelected(true);
                            cartItemIds += cartItemListBean.getCartItemList().get(i).getCartItemList().get(n).getId() + ",";

                        }
                    }

                }
            }
        } else {
            /*取消全选*/
            cartItemListBean.setAllSelect(false);
            for (int i = 0; i < cartItemListBean.getCartItemList().size(); i++) {
                cartItemListBean.getCartItemList().get(i).setSelected(false);
                for (int n = 0; n < cartItemListBean.getCartItemList().get(i).getCartItemList().size(); n++) {
                    cartItemListBean.getCartItemList().get(i).getCartItemList().get(n).setSelected(false);
                }
                allCount = 0;
                allMoney = null;
            }
            cartItemIds = "";
        }
        if (allMoney != null) {
            allMoney = allMoney.setScale(2, BigDecimal.ROUND_DOWN);
        }
        cartItemListBean.setAllMoney(allMoney);
        cartItemListBean.setAllCount(allCount);
        cartItemListBean.setCartItemIds(cartItemIds);
        update(cartItemListBean.isAllSelect(), allCount, allMoney);
        mRefreshAdapter.notifyDataSetChanged();
    }

    @Override
    public void update(boolean isAllSelected, int count, BigDecimal price) {
        if (cartItemListBean.isAllSelect() == true) {
            select_num.setText("全选(" + count + ")");
        } else {
            select_num.setText("已选(" + count + ")");
        }

        if (price != null) {
            mTvAllMoney.setText("¥ " + price);

        } else {
            mTvAllMoney.setText("¥ 0.00");
        }
        mCbSelectAll.setChecked(isAllSelected);
    }

    HttpListener httpListener = new HttpListener() {

        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                closeLoadingDialog();
                cartItemListBean = JsonUtil.parseJsonToBean(response, CartItemListBean.class);
                dataBean = cartItemListBean.getCartItemList();
                if (dataBean.size() == 0) {
                    if (isShow == false) {
                        layout_no_comment.setVisibility(View.GONE);
                        tvRight.setVisibility(View.VISIBLE);
                    } else {
                        tvRight.setVisibility(View.GONE);
                        layout_no_comment.setVisibility(View.VISIBLE);
                        img_no_comment.setImageResource(R.drawable.img_my_shopping_cart);
                    }
                }
                mRefreshAdapter.addDate(cartItemListBean);
                mExpandableListView.setAdapter(mRefreshAdapter);
                //展开所有的分组
                for (int i = 0; i < cartItemListBean.getCartItemList().size(); i++) {
                    mExpandableListView.expandGroup(i);
                }

                String cartNotice = JsonUtil.getFieldValue(response, "cartNotice");
                if (cartNotice != null) {
                    shopping_cart_message.setVisibility(View.VISIBLE);
                    text_msg.setText(cartNotice);
                } else {
                    shopping_cart_message.setVisibility(View.GONE);
                }

            } else {
                closeLoadingDialog();
                toast(errMsg);
            }


        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            closeLoadingDialog();
            toast("加载失败");
        }
    };


    private void initPullrefresh() {
        MessageBean bean = new MessageBean();
        bean.setToken(token);
        bean.setUserId(userId);
        CommonInterface messageInterface = new CommonInterface(MyShoppingCartsActivity.this, httpListener);
        messageInterface.getInterface("16032", JSON.toJSONString(bean));
    }

    /*删除购物车条目*/
    HttpListener deleteHttpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                ToastUtil.showToast("宝贝删除成功");
                initPullrefresh();
                mTvAllMoney.setText("¥0.00");
                select_num.setText("全选(0)");

            } else {
                ToastUtil.showToast(errMsg);
            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            ToastUtil.showToast("删除失败");
        }
    };
}
